package com.niit.mobileDevide.datausage;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class DataUsageMapper extends Mapper<LongWritable, Text, Text, DataUsageBean> {

    private static final int DATA_USAGE_INDEX = 7; // 数据使用量索引
    private static final int NUM_APPS_INSTALLED_INDEX = 6; // 已安装应用数量索引

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length < 8) { // 确保至少有8个字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 解析数据使用量和已安装应用数量
            double dataUsage = Double.parseDouble(columns[DATA_USAGE_INDEX].trim());
            int numAppsInstalled = Integer.parseInt(columns[NUM_APPS_INSTALLED_INDEX].trim());

            // 只输出符合条件的用户
            if (dataUsage > 2000 && numAppsInstalled > 40) {
                DataUsageBean bean = new DataUsageBean(0, 0, 0, numAppsInstalled, dataUsage);
                context.write(new Text("HighDataUsage"), bean); // 使用固定键以便在Reducer中处理
            }

        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}